<template>
  <div class="panel-data">
    <div class="content">
      <PanelLabelOverflowTooltip ref="panelLabelOverflowTooltip" />
      <el-form
        ref="form"
        v-panel-label-overflow-tooltip="getPanelLabelOverflowTooltip()"
        class="prop-form"
        label-position="right"
        :model="form"
        :rules="rules"
        label-width="35%"
      >
        <el-radio-group
          v-model="form.type"
          class="type-choice"
          size="default"
          :fill="activeColorRadio"
          @change="changeDataType"
        >
          <el-radio label="custom">{{ $demoi18n('panelData.dataFromType.custom') }}</el-radio>
          <el-radio label="dataSource">{{ $demoi18n('panelData.dataFromType.api') }}</el-radio>
        </el-radio-group>

        <!-- 自定义模块 -->
        <div
          v-if="form.type === 'custom'"
          class="tool-box"
        >
          <el-button
            type="primary"
            icon="Plus"
            size="default"
            class="addBtn btn-sure"
            @click.stop="addTableRow()"
          >
            {{ $demoi18n('btn.add') }}
          </el-button>
        </div>

        <el-table
          v-if="form.type === 'custom'"
          :data="form.customTableData"
          style="width: 100%"
          size="default"
          class="config-panel-table"
          :tooltip-effect="xvueTheme"
        >
          <el-table-column
            prop="name"
            :label="$demoi18n('panelData.explain.optionName')"
            min-width="100"
            :render-header="renderTableHeader"
          >
            <template #default="scope">
              <VsFormItem
                :prop="`customTableData[${scope.$index}].name`"
                :rules="
                  generateRules({
                    required: false,
                    label: $demoi18n('panelData.explain.optionName'),
                  })
                "
              >
                <el-input
                  v-model="scope.row.name"
                  size="default"
                ></el-input>
              </VsFormItem>
            </template>
          </el-table-column>
          <el-table-column
            prop="key"
            :label="$demoi18n('panelData.explain.filterVal')"
            min-width="100"
            :render-header="renderTableHeader"
          >
            <template #default="scope">
              <VsFormItem
                :prop="`customTableData[${scope.$index}].key`"
                :rules="
                  generateRules({
                    required: false,
                    label: $demoi18n('panelData.explain.filterVal'),
                  })
                "
              >
                <el-input
                  v-model="scope.row.key"
                  size="default"
                ></el-input>
              </VsFormItem>
            </template>
          </el-table-column>
          <el-table-column
            prop="isCheck"
            :label="$demoi18n('panel.label.default')"
            width="50"
            align="center"
            :render-header="renderTableHeader"
          >
            <template #default="scope">
              <el-checkbox
                v-model="scope.row.isCheck"
                size="default"
                @change="isCheckChange(scope.row, scope)"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column
            prop="icon"
            :label="$demoi18n('word.operation')"
            width="70"
            :render-header="renderTableHeader"
          >
            <template #default="scope">
              <el-button
                icon="SortUp"
                :link="true"
                type="primary"
                :disabled="scope.$index === 0"
                @click.stop="moveUp(scope.$index, scope.row)"
              ></el-button>
              <el-button
                icon="SortDown"
                :link="true"
                type="primary"
                style="margin-left: 1px;"
                :disabled="scope.$index === form.customTableData.length - 1"
                @click.stop="moveDown(scope.$index, scope.row)"
              ></el-button>
              <el-button
                class="icon"
                :link="true"
                type="primary"
                icon="Delete"
                style="margin-left: 1px;"
                @click.stop="deleteItem(scope)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="explain"
            :label="$demoi18n('panel.th.explain')"
            min-width="36"
            :render-header="renderTableHeader"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              <span>{{ $demoi18n(scope.row.explain) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 数据获取模块 -->
        <div v-else-if="form.type === 'dataSource'">
          <panel-data
            ref="panelDataCommon"
            :config="config"
            :widget-instance-id="widgetInstanceId"
            :data-source-type-options="isAurora ? auroraDataSourceTypeOptions : dataSourceTypeOptions"
            :is-aurora="isAurora"
            :dataForm="form"
          >
          </panel-data>
        </div>

        <div
          v-if="form.type === 'dataSource'"
          class="defaultVal_box"
        >
          <VsFormItem :label="$demoi18n('word.defaultValue')">
            <el-switch v-model="form.hasDefaultVal"></el-switch>
          </VsFormItem>
          <VsFormItem
            v-if="form.hasDefaultVal"
            :label="$demoi18n('panelData.label.dfValSource')"
          >
            <el-select
              v-model="form.defaultValFrom"
              size="default"
            >
              <el-option
                :label="$demoi18n('panelData.option.firstData')"
                value="first"
              ></el-option>
              <el-option
                :label="$demoi18n('panelData.option.lastData')"
                value="last"
              ></el-option>
              <el-option
                :label="$demoi18n('panelData.option.custom')"
                value="custom"
              ></el-option>
              <el-option
                :label="$demoi18n('select.panel-data.fromEventLinkage')"
                value="event"
              ></el-option>
            </el-select>
          </VsFormItem>
          <VsFormItem
            v-if="form.hasDefaultVal && form.defaultValFrom === 'custom'"
            :label="$demoi18n('panelData.label.setDefault')"
            prop="defaultVal"
            :rules="
              generateRules({
                required: false,
                label: $demoi18n('panelData.label.setDefault'),
              })
            "
          >
            <ValueInputer
              v-model:value="form.defaultVal"
              :enum-values="apiDataVals"
            />
          </VsFormItem>
          <VsFormItem
            v-if="form.hasDefaultVal && form.defaultValFrom === 'event'"
            :label="$demoi18n('select.panel-data.settingDefaultEvents')"
            :helptip="$demoi18n('select.panel-data.defaultValEventTip')"
            prop="defaultValEvent"
            :rules="
              generateRules({
                required: true,
                label: $demoi18n('select.panel-data.settingDefaultEvents'),
              })
            "
          >
            <el-select v-model="form.defaultValEvent" multiple :placeholder="$demoi18n('word.plsSelect')">
              <el-option
                v-for="item in configEvents"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </VsFormItem>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script lang='jsx'>
import { auroraDataSourceTypeOptions, dataSourceTypeOptions } from '@/common/panel_config';
import PanelLabelOverflowTooltip from '@/components/common/overflow-tooltip/overflow-tooltip.vue';
import ValueInputer from '@/components/common/value-inputer/value-inputer.vue';
import VsFormItem from '@/components/common/vs-form-item/vs-form-item.vue';
import PanelData from '@/components/panel-data/panel-data-common';
import xTagBase from '@/components/panel-data/xtag-base.js';
import panelDataBase from '@/mixin/panel-data-base.js';
import { generateRules } from '@/utils/rules';
import { mapState } from 'vuex';

/**
 * config  整体配置项
 */
export default {
  name: 'SelectPanelData',
  components: { PanelData, ValueInputer, PanelLabelOverflowTooltip, VsFormItem },
  mixins: [xTagBase, panelDataBase],
  props: ['config', 'widgetInstanceId', 'dataForm'],
  data() {
    const form = JSON.parse(JSON.stringify(this.config.config.data));
    return {
      dataSourceTypeOptions,
      auroraDataSourceTypeOptions,
      isAurora: this.$platformName === 'Aurora',
      activeColorRadio: '#2D8CF0', // 单选框选中时的颜色
      form,
      apiData: [], // 接口请求结果
      xvueTheme: window._adoPremise.uc.theme,
    };
  },
  computed: {
    ...mapState({
      panelApiData: state => state.VisualComponentsModule.panelApiData,
      panelConfigs: state => state.VisualComponentsModule.panelConfigs,
    }),
    apiDataVals() {
      const arr = this.panelApiData.map(n => ({
        label: `${n.name} (${n.key})`,
        value: n.key,
      }));
      return Array.from(new Set(arr));
    },
    configEvents() {
      const configEvents = Array.isArray(this.panelConfigs[this.widgetInstanceId]?.events) ? this.panelConfigs[this.widgetInstanceId]?.events : [];
      const events = configEvents.filter(event => event.type === 'in' && event.key).map(event => ({ label: event.key, value: event.key, id: event.id }));
      return events;
    },
  },
  watch: {
    'config.config.property.multiple'(newVal, oldVal) {
      this.clearCheckStatus();
    },
  },
  methods: {
    generateRules,
    getPanelLabelOverflowTooltip() {
      return {
        parentComp: this,
      };
    },
    clearCheckStatus() {
      this.form.customTableData.forEach(item => {
        item.isCheck = false;
      });
    },
    isCheckChange(row, scope) {
      const isCheck = JSON.parse(JSON.stringify(row.isCheck));
      const { multiple } = this.config.config.property;
      if (!multiple) {
        this.clearCheckStatus();
      }
      this.form.customTableData[scope.$index] = {
        ...this.form.customTableData[scope.$index],
        isCheck: isCheck,
      };
    },
    addTableRow() {
      this.form.customTableData.push({
        name: '',
        key: '',
        isCheck: false,
      });
    },
    moveUp(index) {
      if (index > 0) {
        const temp = this.form.customTableData[index - 1];
        this.form.customTableData.splice(index - 1, 1);
        this.form.customTableData.splice(index, 0, temp);
      }
    },
    moveDown(index) {
      const temp = this.form.customTableData[index + 1];
      this.form.customTableData.splice(index + 1, 1);
      this.form.customTableData.splice(index, 0, temp);
    },
    deleteItem(scope) {
      const index = scope.$index;
      this.form.customTableData.splice(index, 1);
    },
    renderTableHeader({ column }) {
      return (
        <el-tooltip placement="top" content={column.label} effect={this.xvueTheme}>
          <span>{column.label}</span>
        </el-tooltip>
      );
    },
    changeDataType(type) {
      // 清除datasource的配置
      if (type === 'custom') {
        this.form.dataSourceType = '';
        this.form.dataSource = '';
        this.form.apiCode = '';
        this.form.dataPackage = '';
        this.form.dataTable = '';
        this.form.redisKey = '';
        this.form.tableData = [
          {
            field: 'name',
            mapping: '',
            explain: 'panelData.explain.optionName',
          },
          {
            field: 'key',
            mapping: '',
            explain: 'panelData.explain.filterVal',
          },
          {
            field: 'label',
            mapping: '',
            explain: 'panelData.explain.filterGroup',
            skipVerification: true,
          },
        ];
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import '../../common/overflow-tooltip/el-form-item-label-tooltip.less';
</style>
<style lang="less" scoped>
.panel-data {
  .content {
    padding: 0 10px;
    .config-panel-table {
      :deep(.el-form-item) {
        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
      :deep(.cell) {
        padding: 0 3px !important;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .type-choice {
      margin-bottom: 8px;
    }
    .tool-box {
      width: 100%;
      margin-bottom: 8px;
      .addBtn {
        padding: 6px 12px;
        border-radius: 5px;
      }
    }

    .icon {
      padding: 0;
    }

    .prop-form {
      :deep(.el-form-item) {
        margin-bottom: 0;
      }
    }
    .defaultVal_box {
      margin-top: 10px;
      :deep(.el-radio) {
        margin-right: 10px;
      }
      .value-inputer {
        display: inline-block;
      }
    }
  }
}
</style>

<style lang="less">
.panel-data-select-dark {
  :deep(.el-input) {
    .el-input__inner {
      border-color: #588ba8;
      color: #fff;
      background-color: #091a2d;
    }
    .el-input__icon {
      color: #588ba8;
    }
  }
}

.select-poper-dark {
  background-color: #091a2d;
  border-color: #588ba8;

  :deep(.el-scrollbar) {
    .el-select-dropdown__list {
      .el-select-dropdown__item {
        padding: 0 12px;
        height: 24px;
        line-height: 24px;
        font-size: 12px;
        color: #fff;
        background-color: #091a2d;

        .select-icon {
          margin-left: 0;
          padding: 0;
        }

        .select-option-slot-text {
          display: inline-block;

          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          color: #178ddf;
        }
        .select-option-slot-icon {
          display: inline-block;
          vertical-align: top;
        }
      }
      .hover {
        background-color: #102e4f;
      }
    }
  }
  :deep(.popper__arrow) {
    border-bottom-color: #588ba8;
    &::after {
      border-bottom-color: #091a2d !important;
    }
  }
}

.select-poper-light {
  :deep(.el-scrollbar) {
    .el-select-dropdown__list {
      .el-select-dropdown__item {
        padding: 0 12px;
        height: 24px;
        line-height: 24px;
        font-size: 12px;

        .select-icon {
          margin-left: 0;
          padding: 0;
        }

        .select-option-slot-text {
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .select-option-slot-icon {
          display: inline-block;
          vertical-align: top;
        }
      }
    }
  }
}
</style>

<style lang="less" scoped>
.dark {
  .defaultVal_box {
    color: #98cae6;
  }
}
</style>
